package com.jbp.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbp.dao.UserCreatorDao;
import com.jbp.exception.RRException;
import com.jbp.model.User;
import com.jbp.model.UserCreator;
import com.jbp.model.UserLevel;
import com.jbp.model.Wallet;
import com.jbp.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

@Service
public class UserCreatorService extends ServiceImpl<UserCreatorDao, UserCreator> implements IService<UserCreator> {
    @Autowired
    private UserLevelService userLevelService;
    @Autowired
    private UserService userService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private TecentMsgService tecentMsgService;
    @Value("${xiaohao.namePrex}")
    private String namePrex;
    @Value("${istest}")
    private String istest;

    public boolean isCreator(int userId){
        LambdaQueryWrapper<UserCreator> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserCreator::getUserId, userId);
        return count(lqw) > 0;
    }



    public String createXiaoHao(Integer userId) {
        if (!isCreator(userId)) {
            throw new RRException("没有权限");
        }
        String chars = "abcdefghijklmnopkrstuvwxyz";
        String pwd = "";

        Random rand = new Random();//生成随机数
        String name = namePrex;// + chars.charAt(rand.nextInt(chars.length()));
        for (int i = 0; i < 2; i++) {
            int num = rand.nextInt(chars.length());
            pwd += chars.charAt(num);
            pwd += chars.charAt(num);
        }

        for (int a = 0; a < 2; a++) {
            int k = rand.nextInt(10);
            pwd += k;
            pwd += k;
        }

        System.out.println("创建账号");
        StringBuilder sb = new StringBuilder();
        for (int m = 1; m < 11; m++) {
            String phone = MobileUtil.getMobile();
            boolean flag = createUser(phone, pwd, name, userId);
            if (flag) {
                sb.append(""+phone+"    "+pwd).append("\n");
            }
        }
        return sb.toString();
    }

    public boolean createUser(String phone, String pwd, String name, int upUserId) {
        User user = userService.getOne(new QueryWrapper<User>().eq("mobile", phone));
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            String code = UUIDUtil.inviteCode();
            while (true) { //确保邀请码唯一
                if(!userService.isCodeExits(code)) {
                    user.setCode(code);
                    break;
                } else {
                    code = UUIDUtil.inviteCode();
                }
            }
            user.setSalt(code);
            /**
             * 生成靓号
             */
            String uuid= CreateUUid.createCode();
            while (true) { //确保uuid唯一
                if(!userService.isUuidExits(uuid)) {
                    user.setUuid(uuid);
                    break;
                } else {
                    uuid = CreateUUid.createCode();
                }
            }
            user.setIsOnline("online");
            user.setCreateTime(new Date());
            user.setPassword(StrToMillsUtil.passwordEncode(pwd, user.getSalt()));
            user.setTemps(pwd);
            user.setCreateType(2);//小号
            user.setUpUserId(upUserId);

            Random rands = new Random();
            int r = rands.nextInt(3);
            if (r == 1) {
                user.setSex("man");
            }else {
                user.setSex("women");
            }

            /*Random rand = new Random();
            for(int a=0;a<5;a++){
                name += rand.nextInt(10);
            }*/

            //新规则生成机器人名字，或新建账号名字
            name = RobNameUtil.getRobName();
            user.setName(name);
            boolean save = userService.save(user);

            if (save) {
                UserCreator userCreator = new UserCreator();
                userCreator.setUserId(user.getId());
                userCreator.setCreateTime(new Date());
                userCreator.setName(user.getName());
                userCreator.setPhone(phone);
                userCreator.setPassword(pwd);
                this.save(userCreator);

                Wallet wallet = new Wallet();
                wallet.setUserId(user.getId());
                wallet.setXinzuan(BigDecimal.valueOf(0));
                wallet.setCreateTime(new Date());
                walletService.save(wallet);

                if (!"test".equals(istest)) {
                    tecentMsgService.addUser(user.getId(), false);
                }
                return true;
            }
        }
        return false;
    }

    public User createRob(String phone, String name) {
        User user = userService.getOne(new QueryWrapper<User>().eq("mobile", phone));
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            /**
             * 生成靓号
             */
            String uuid= CreateUUid.createCode();
            while (true) { //确保uuid唯一
                if(!userService.isUuidExits(uuid)) {
                    user.setUuid(uuid);
                    break;
                } else {
                    uuid = CreateUUid.createCode();
                }
            }
            user.setIsOnline("online");
            user.setCreateTime(new Date());
            user.setCreateType(1);//机器人
            user.setUpUserId(10);

            /*Random rand = new Random();
            for(int a=0;a<5;a++){
                name += rand.nextInt(10);
            }*/

            //新规则生成机器人名字，或新建账号名字
            name = RobNameUtil.getRobName();

            user.setName(name);
            boolean save = userService.save(user);
            //机器人等级
            UserLevel userLevel = new UserLevel();
            userLevel.setUserId(user.getId());
            userLevel.setCreateTime(new Date());
            Random random = new Random();
            int lev = random.nextInt(7) + 3;
            userLevel.setLevel(lev);
            userLevel.setScore(lev);
            userLevel.setUpdateTime(new Date());
            userLevelService.save(userLevel);
            if (save) {
                user.setLevel(lev);
                userService.updateById(user);

                tecentMsgService.accountImport(user);

                return user;
            }
        }
        return null;
    }
}